using Gdk;
using Gtk;
using irex;
using Posix;

public class Package : GLib.Object {
    public string name;
    public string version;

    Package(string name, string version) {
        this.name = name;
        this.version = version;
    }
}

public class ValaTest : GLib.Object, irex.Application {

    irex.IPC ipc;
    irex.Menu mainMenu;
    Gtk.Window mainWin;

    /**
     * Initialise our app, create IPC connection and main menu
     */
    construct {
        ipc = new irex.IPC("valatest", "1.0", this);
        var mm = new irex.MenuManager(ipc);
        mainMenu = new irex.Menu(mm, "mainmenu", "Stupendous Menu");
        var group = mainMenu.addGroup("awesome", "Awesome Buttons");
        group.addItem("close", "Close", "close");
        group.addItem("cheese", "Cheese!", "cut");
        mainMenu.realise();
        mainMenu.show();
    }

    /**
     * Create app ui, then inform sysd we're ready
     */
    public void run(string[] args) {
        try {
            var builder = new Builder();
            builder.add_from_file(getAppPath(args[0])+"/main.ui");
            mainWin = builder.get_object("window1") as Gtk.Window;
            setup_treeview (builder.get_object ("treeview1") as TreeView);
            mainWin.show_all();
            mainWin.destroy += Gtk.main_quit;
            ipc.send_startup_complete();
        } catch (Error e) {
            stdout.printf("Failed to load ui: %s\n", e.message);
            Gtk.main_quit();
        }
    }

    List<Package> read_packages() {
        List<Package> packages = new List<Package>();
        Posix.system("opkg list_installed > /tmp/pkglist");
        var file = File.new_for_path("/tmp/pkglist");
        var in_stream = new DataInputStream (file.read (null));
        string line;
        while ((line = in_stream.read_line (null, null)) != null) {
            string[] vals = line.split(" - ");
            if (vals.length>1)
                packages.append(new Package(vals[0], vals[1]));
        }
        return packages;
    }

    private void setup_treeview (TreeView view) {
        List<Package> packages = read_packages();

        var listmodel = new ListStore (2, typeof (string), typeof (string));
        view.set_model (listmodel);
        view.insert_column_with_attributes (-1, "Name", new CellRendererText (), "text", 0, null);
        view.insert_column_with_attributes (-1, "Version", new CellRendererText (), "text", 1, null);
        TreeIter iter;
        foreach (Package p in packages) {
            listmodel.append (out iter);
            listmodel.set (iter, 0, p.name, 1, p.version, -1);
        }
    }

    /**
     * Implement irex.Application::getMainWindow
     */
    public Gtk.Window getMainWindow() {
        return this.mainWin;
    }

    /**
     * Implement irex.Application::onMenuClick
     */
    public void onMenuClick(string item, string group, string menu, string state) {
        stdout.printf("onMenuClick: %s %s %s %s\n", item, group, menu, state);
        if (item=="close") {
            Gtk.main_quit();
        }
    }
        
    /**
     * Implement irex.Application::onFileOpen
     */
    public bool onFileOpen(string filename, out int xid, out string error) { 
        stdout.printf("onFileOpen: %s\n", filename);
        //int my_xid = (int)Gdk.x11_drawable_get_xid(mainWin.window);
        return true; 
    }

    /**
     * Implement irex.Application::onFileClose
     */
    public bool onFileClose(string filename) { 
        stdout.printf("onFileClose: %s\n", filename);
        return true; 
    }
    
    /**
     * Implement irex.Application::onWindowChange
     */
    public void onWindowChange(int xid, bool activated) {
        stdout.printf("onWindowChange: %d, %d\n", xid, (int)activated);
        if (activated)
            mainMenu.show();
    }

    public void onPrepareUnmount(string device) {}
    public void onUnmounted(string device) {}
    public void onMounted(string device) {}
    public void onPrepareHibernate() {}
    public void onChangedLocale(string locale) {}
    public void onChangedOrientation(string orientation) {}

    /**
     * Helper function to get app path
     */
    string getAppPath(string arg0) {
        int pathidx = (int)arg0.pointer_to_offset(arg0.rchr(-1,'/'));
        return arg0.substring(0, pathidx);
    }

    /**
     * Main entry point
     */
    static int main (string[] args) {
        Gtk.init (ref args);
        var test = new ValaTest();
        test.run(args);
        Gtk.main ();
        return 0;
    }
}
